$(function () {//加载表格
    getBaseDataTree();
    treeSearch("ss", "treeContent"); // 绑定树搜索功能
    initData();
    comboboxChanageDemandBug();
    $('#onlyColumn').combobox({
        formatter: function (row) {
            return '<span  class="item-text">' + row.value + "_" + row.showmsg + '</span>';
        }
    });
    $('#showColumnConfig').combobox({
        formatter: function (row) {
            return '<span class="item-text">' + row.value + "_" + row.showmsg + '</span>';
        }
    });
    $('#primaryKeyColumnReal').combobox({
        formatter: function (row) {
            return '<span class="item-text">' + row.value + "_" + row.showmsg + '</span>';
        }
    });
    $('#selectColumn').combobox({
        formatter: function (row) {
            return '<span class="item-text">' + row.value + "_" + row.showmsg + '</span>';
        }
    });
    $('#orderColumn').combobox({
        formatter: function (row) {
            return '<span class="item-text">' + row.value + "_" + row.showmsg + '</span>';
        }
    });
});

/**
 * 加载功能树
 */
function getBaseDataTree() {
    //加载机构树，当前登录人所在的机构信息
    $.messager.progress({text: '正在加载中...',});
    $.ajax({
            type: "post",
            url: reportworld + "/dataBase/queryDatabaseTree",
            dataType: "json",
            success: function (data) {
                $.messager.progress('close');
                if (successcode != data.code) {
                    return errorHandle(data);
                }
                getDataBasegrid("RW_DB_TP_GL_EXHIB_DATADICT", "字典数据列表", "dg");
                $('#treeContent').tree({
                    cascadeCheck: false,
                    checkbox: false,
                    lines: false,
                    data: data.data,
                    onClick: function (node) {
                        if (node.pid == 0) {
                            return;
                        }
                        getDataBasegrid(node.attributes, node.text + "列表", "dg");
                    },  //双击事件
                    onDblClick: function (node) {

                    }, onContextMenu: function (e, node) {
                        //显示上下文菜单:就是显示右键菜单
                        e.preventDefault();
                        $(this).tree('select', node.target);
                        $('#nav').menu('show', {
                            left: e.pageX,
                            top: e.pageY
                        });
                        $('#nav').menu({
                            onClick: function (item) { // 根据选择的id判断选中的是添加，修改，还是删除
                                if ("1" == item.id) {
                                    addDataBase();
                                }
                                if ("2" == item.id) {
                                    editDataBase();
                                }
                                if ("3" == item.id) {
                                    delDataBase();
                                }
                                if ("4" == item.id) {
                                    viewBasedataConfig(node);
                                }
                            }
                        })
                        $("#4").show();
                        if (node.pid == 0) { // 最上级不显示配置管理
                            $("#4").hide()
                        }
                    },
                    formatter: function (node) {
                        //显示父节点含有子节点个数
                        var s = node.text;
                        if (node.children) {
                            s += ' <span style=\'color:blue\'>(' + node.children.length + ')</span>';
                        }
                        return s;
                    }
                });
            }, error: function (data) {
                $.messager.progress('close');
                $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
            }
        }
    );
}

// 初始化加载下拉框的值
function initData() {
    $.ajax({
            type: "post",
            url: reportworld + "/dataBase/init",
            dataType: "json",
            success: function (data) {
                if (successcode != data.code) {
                    return errorHandle(data);
                }
                // 所属模块
                var listModular = data.data.listModular;
                // 所属客户
                var listCustomer = data.data.listCustomer;
                //所属报表
                var listReport = data.data.listReport;
                //版本号
                var listVersion = data.data.listVersion;
                //状态
                var listStatus = data.data.listStatus;
                //数据库类型
                var listReportDataBaseType = data.data.listReportDataBaseType;
                // 基础数据树数据
                var databaseTree = data.data.databaseTree;
                //当前版本的bug和需求
                var demandBugInfoList = data.data.demandBugInfoList;
                if (!isNull(listModular)) {
                    $("#strModular").combotree("loadData", listModular);
                    $('#updateModular').combotree({data: listModular});
                }
                if (!isNull(listCustomer)) {
                    $("#strCustomer").combotree("loadData", listCustomer);
                    $('#updateCustomer').combotree({data: listCustomer});
                }
                if (!isNull(listReport)) {
                    $("#strReport").combotree("loadData", listReport);
                    $('#updateReport').combotree({data: listReport});
                }
                if (!isNull(listVersion)) {
                    // $("#databaseUpdateVersion").combobox("loadData", listVersion);
                    $("#rwDbVersion").combobox("loadData", listVersion);
                }
                if (!isNull(listStatus)) {
                    $("#rwDbStatus").combobox("loadData", listStatus);
                    $("#statusConfig").combobox("loadData", listStatus);
                    var listStatus2 = data.data.listStatus2;
                    listStatus2.unshift({"showmsg": "==全部==", "value": ''});
                    $("#selRwDbStatus").combobox("loadData", listStatus2);
                }
                if (!isNull(listReportDataBaseType)) {
                    $("#dataBaseType").combobox("loadData", listReportDataBaseType);
                }
                if (!isNull(demandBugInfoList)) {  //需求BUG
                    $("#demandBugInfo").combobox("loadData", demandBugInfoList);
                }
                if (!isNull(databaseTree)) {
                    //在数组第一个追加
                    databaseTree.unshift({"text": "==无上级==", "id": '0', "pId": "", "iconCls": "icon-bricks"});
                    $("#parentId").combotree("loadData", databaseTree);
                }
            }, error: function (data) {
                $.messager.progress('close');
                $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
            }
        }
    );
}

// 表格的字段信息
var columns;
var arrHideColumn = ["MODULAR", "REPORT", "CUSTOMER", "RW_DB_STATUS", "RW_DB_ID"];

// 获取要查询的数据库字段
function getDataBasegrid(databaseCode, title, datagrid) {
    columns = [];
    var array = [];
    $.ajax({
            type: "post",
            url: reportworld + "/dataBase/getDataBaseColumnNames",
            dataType: "json",
            data: {
                code: databaseCode
            },
            success: function (data) {
                if (successcode != data.code) {
                    return errorHandle(data);
                }
                // 加入多选框
                array.push({field: 'itemid', title: 'Order ID', width: '80', checkbox: true});
                $.each(data.data, function (index2, item2) {
                    array.push({field: '', title: ''/*, width: ''*/});
                });
                columns.push(array);
                var i = 1;
                $.each(data.data, function (index2, item2) {
                    columns[0][i]['field'] = index2;
                    columns[0][i]['title'] = item2;
                    columns[0][i]['width'] = "150";
                    for (var hideColumn in arrHideColumn) {
                        if (index2 == arrHideColumn[hideColumn]) {
                            columns[0][i]['hidden'] = true;
                        }
                    }
                    // RW_DB_TP_GL_PB_TAG表的SELECT_LIST点击查询字典
                    if ("RW_DB_TP_GL_PB_TAG" == databaseCode && "SELECT_LIST" == index2) {
                        columns[0][i]['formatter'] = function formatterDic(value, row, index) {
                            if (row.PLACE_HOLDER.indexOf("请选择") > -1 && "VARCHAR2" == row.COLUM_TYPE && !isNull(row.SELECT_LIST)) {
                                return "<a href='javascript:void(0)' onclick='datagridDataDic(&apos;" + row['SELECT_LIST'] + "&apos;)'>" + row.SELECT_LIST + "</a>";
                            } else {
                                return row.SELECT_LIST;
                            }
                        };
                    }
                    i++;
                });
                getDatagrid(databaseCode, title, datagrid);
            }, error: function (data) {
                $.messager.progress('close');
                $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
            }
        }
    );
}

/**
 * 对应的配置信息
 */
var dataBaseConfig;
/**
 * 库里每个列对应的数据库类型
 */
var columnNames;
/**
 * 判断是不是当前基础数据编码
 */
var codeOld;

//数据列表
function getDatagrid(databaseCode, title, datagrid) {
    $("#" + datagrid).datagrid({
        loadMsg: '数据加载中，请稍后...',
        queryParams: {
            code: databaseCode
        },
        url: reportworld + "/dataBase/getDataBasegrid",
        pagination: true,
        singleSelect: false,//如果为true，则只允许选择一行。
        title: title,
        pageSize: pageSize,
        pageList: pageList,
        checkOnSelect: true,//当用户点击行的时候该复选框就会被选中或取消选中。
        striped: true,//是否显示斑马线效果。
        rownumbers: true,// 显示一个行号列
        fitColumns: false,//真正的自动展开/收缩列的大小，以适应网格的宽度，防止水平滚动。
        columns: columns,
        loadFilter: function (data) {
            if (successcode != data.code) {
                return errorHandle(data);
            }
            dataBaseConfig = data.data.dataBaseConfig; // 配置信息
            columnNames = data.data.columnNames; // 字段对应的数据库类型
            // 添加查询条件
            var html = "<tr>";
            if (isNull(dataBaseConfig.selectColumn)) { // 没有配置的清楚查询条件
                $("#showColumn tr").remove();
            } else if (codeOld != dataBaseConfig.code) {
                codeOld = dataBaseConfig.code;
                $("#showColumn tr").remove();
                var arrSelectColumn = JSON.parse(dataBaseConfig.selectColumn);
                var showColumn = JSON.parse(dataBaseConfig.showColumn);
                var jslength = 0;
                for (var js2 in arrSelectColumn) {
                    jslength++;
                }
                // 从查询字段信息里获取对应的列中文名称
                var i = 0;
                var htmlSearch = "";
                for (var columnName in arrSelectColumn) {
                    if (i % 3 == 0) {
                        html += " </tr><tr>";
                    }
                    if (i == jslength - 1) {
                        htmlSearch = " <a class=\"easyui-linkbutton\" iconCls='icon-search' onclick=\"doSearch();\">查询</a>"
                    }
                    var title = showColumn[columnName];
                    if ("VARCHAR" == columnNames[columnName] || "DECIMAL" == columnNames[columnName] || "LONGTEXT" == columnNames[columnName]) {
                        html += "<td>" + title + "：</td>" +
                            "<td><input class='easyui-validatebox' style='width: 150px' id='RW_DB_" + columnName + "' name='RW_DB_" + columnName + "'/>" +
                            htmlSearch + "</td>";
                    } else if ("DATE" == columnNames[columnName]) {
                        html += "<td>" + title + "：</td>" +
                            "<td><input editable='false' class='easyui-datebox' data-options='showSeconds:false' style='width: 150px' " +
                            "id='RW_DB_" + columnName + "' name='RW_DB_" + columnName + "'/>" + htmlSearch + "</td>";
                    } else if ("DATETIME" == columnNames[columnName] || "TIMESTAMP" == columnNames[columnName]) {
                        html += "<td>" + title + "：</td>" +
                            "<td><input editable='false' class='easyui-datetimebox' data-options='showSeconds:true' style='width: 150px'" +
                            " id='RW_DB_" + columnName + "' name='RW_DB_" + columnName + "'/>" + htmlSearch + "</td>";
                    }
                    i++;
                }
                html += " </tr>";
                $("#showColumn").append(html);
                $.parser.parse('#showColumn');//重新渲染页面，解决样式不生效
            }
            return data.data;
        },
        //双击事件
        onDblClickRow: function (rowIndex, rowData) {
            viewBasedataInfo(rowData)
        }
        ,
        //表格样式
        rowStyler: function (index, row) {
            return rowStyler(row.RW_DB_STATUS);
        }
    }).datagrid("columnMoving");
    ;
}


/**
 *  页面显示信息
 * @param rowData
 */
function viewBasedataInfo(rowData) {
    $("#databaseview").show();
    $("#myfromdatabase").form('clear');//添加之前清空表达信息
    $('#dlg').dialog({
        title: "查看数据详细信息",
        buttons: [{
            text: '返回',
            iconCls: 'icon-back',
            handler: function () {
                $('#dlg').dialog('close');
            }
        }
        ]
    }).dialog('open');
    addViewData();
    $('#rwDbVersion').combobox('selectedIndex', 0); //选中第一个
    $('#rwDbStatus').combobox('selectedIndex', 0); //选中第一个
    $('#myfromdatabase').form('load', rowData);//页面赋值
}

/**
 *  修改弹出页面
 */
function editBasedataInfo() {
    var arr = $('#dg').datagrid('getSelections');
    if (null == arr || arr.length != 1) {
        $.messager.alert('系统提示', "请选择一行数据！", 'warning');
        return;
    }
    $("#databaseview").show();
    $("#myfromdatabase").form('clear');//添加之前清空表达信息
    $('#dlg').dialog({
        title: "数据详细信息",
        buttons: [{
            text: '保存',
            iconCls: 'icon-save',
            handler: function () {
                saveItemBaseDateById(arr[0]);
            }
        }, {
            text: '返回',
            iconCls: 'icon-back',
            handler: function () {
                $('#dlg').dialog('close');
            }
        }
        ]
    }).dialog('open');
    addViewData();
    $('#rwDbVersion').combobox('selectedIndex', 0); //选中第一个
    $('#rwDbStatus').combobox('selectedIndex', 0); //选中第一个
    $('#myfromdatabase').form('load', arr[0]);//页面赋值
}

/**
 *  页面显示信息
 * @param rowData
 */
function insertBasedataInfo() {
    $("#databaseview").show();
    $("#myfromdatabase").form('clear');//添加之前清空表达信息
    $('#dlg').dialog({
        title: "数据详细信息",
        buttons: [{
            text: '保存',
            iconCls: 'icon-save',
            handler: function () {
                insertItemBaseDate();
            }
        }, {
            text: '返回',
            iconCls: 'icon-back',
            handler: function () {
                $('#dlg').dialog('close');
            }
        }
        ]
    }).dialog('open');
    addViewData();
    $('#rwDbVersion').combobox('selectedIndex', 0); //选中第一个
    $('#rwDbStatus').combobox('selectedIndex', 0); //选中第一个
}

/**
 * 添加和修改渲染页面
 */
function addViewData() {
    $("#databaseview tr").remove();
    var html = "";
    var fieldArr = columns[0];
    for (var i in fieldArr) {
        var field = fieldArr[i]['field'];
        var title = fieldArr[i]['title'];
        if (isShowHide(field, title)) {
            continue;
        }
        var field = fieldArr[i]['field'];
        var display = "block";
        // 隐藏主键字段
        if (dataBaseConfig.primaryKeyColumn == field) {
            display = "none";
        }
        if (dataBaseConfig.primaryKeyColumnReal == field) {
            display = "none";
        }
        if ("VARCHAR" == columnNames[field] || "DECIMAL" == columnNames[field] || "TEXT" == columnNames[field]) {
            html += "<tr style='display: " + display + "'><td align='right' style='width: 200px'>" + title + "：</td>" +
                "<td><input class='easyui-validatebox' style='width: 150px' id='" + field + "' name='" + field + "'/></td></tr>";
        } else if ("DATE" == columnNames[field]) {
            html += "<tr style='display: " + display + "'><td align='right' style='width: 200px'>" + title + "：</td>" +
                "<td><input editable='false' class='easyui-datebox' data-options='showSeconds:false' style='width: 150px' id='" + field + "' name='" + field + "'/></td></tr>";
        } else if ("DATETIME" == columnNames[field] || "TIMESTAMP" == columnNames[field]) {
            html += "<tr style='display: " + display + "'><td align='right' style='width: 200px'>" + title + "：</td>" +
                "<td><input editable='false' class='easyui-datetimebox' data-options='showSeconds:true' style='width: 150px' id='" + field + "' name='" + field + "'/></td></tr>";
        } else if ("LONGTEXT" == columnNames[field]) {
            html += "<tr style='display: " + display + "'><td align='right' style='width: 200px'>" + title + "：</td>" +
                "<td><input validType='length[10,1200000]'  class='easyui-textbox' data-options='multiline:true' style='width: 550px;height:350px' id='" + field + "' name='" + field + "'/></td></tr>";
        }
    }
    $("#databaseview").append(html);
    $.parser.parse('#databaseview');//重新渲染页面，解决样式不生效
}

/**
 * 保存基础数据
 */
function insertItemBaseDate() {
    $.messager.confirm('系统提示', "确定保存基础数据信息吗？", function (parm) {
        if (!parm) {
            return;
        }
        var fieldArr = columns[0];
        $('#myfromdatabase').form('submit', {
            url: reportworld + "/dataBase/dataBaseInsert",
            onSubmit: function (param) {
                var obj = new Object();
                obj.strModular = getCommbotreeValueDetail("updateModular");
                obj.strCustomer = getCommbotreeValueDetail("updateCustomer");
                obj.strReport = getCommbotreeValueDetail("updateReport");
                param.code = dataBaseConfig.code;
                var jsonStr = getEntityJson(fieldArr, 2);
                obj.entityJson = jsonStr;
                param.queryJson = JSON.stringify(obj);
                $.messager.progress({text: '正在处理中...',});
            }, success: function (data) {
                $.messager.progress('close');
                try {
                    data = JSON.parse(data);
                    if (successcode != data.code) {
                        return errorHandle(data);
                    }
                    //关闭弹出窗口
                    $('#dlg').dialog('close');
                    $.messager.show({title: '系统提示', msg: data.message});
                    $('#dg').datagrid("load");//刷新表格
                } catch (e) {
                    $.messager.progress('close');
                    $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
                }
            }
        });
    });
}

/**
 * 页面数据拼接成JSON格式
 * @param fieldArr
 * @param type
 */
function getEntityJson(fieldArr, type) {
    var jsonStr = "{";
    for (var i in fieldArr) {
        var field = fieldArr[i]['field'];
        var title = fieldArr[i]['title'];
        if (isShowHide(field, title)) {
            continue;
        }
        var fieldValue = $("#" + fieldArr[i]['field']).val();
        if ("LONGTEXT" == columnNames[field]) {
            fieldValue = $("#" + fieldArr[i]['field']).textbox("getValue");
        }
        if (isNull(fieldValue)) {
            fieldValue = "";
        }
        if (fieldValue.indexOf("\"") > -1) {
            fieldValue = fieldValue.replaceAll("\"", "\\\"")
        }
        jsonStr += '"' + fieldArr[i]['field'] + '"' + ":" + '"' + fieldValue + '"' + ",";
    }
    jsonStr += '"RW_DB_VERSION"' + ":" + '"' + $('#rwDbVersion').combobox('getValue') + '",';
    jsonStr += '"RW_DB_STATUS"' + ":" + '"' + $('#rwDbStatus').combobox('getValue') + '",';
    if (1 == type) {
        jsonStr += '"RW_DB_FILE_NAME"' + ":" + '"手工修改"';
    } else {
        jsonStr += '"RW_DB_FILE_NAME"' + ":" + '"手工新增"';
    }
    jsonStr += "}";
    return jsonStr;
}

// 查询和新增页面不显示自定义增加的字段，已经在页面固定添加了
function isShowHide(field, title) {
    if (("itemid" == field && "Order ID" == title)
        || (("STRMODULAR" == field || "STRREPORT" == field || "STRCUSTOMER" == field
            || "MODULAR" == field || "REPORT" == field || "CUSTOMER" == field)
            && ("所属模块" == title || "所属客户" == title || "所属报表" == title))
        || (("STR_RW_DB_VERSION" == field || "RW_DB_VERSION" == field) && "版本号" == title)
        || (("STR_RW_DB_STATUS" == field || "RW_DB_STATUS" == field) && "状态" == title)
        || ("RW_DB_ADD_TIME" == field && "添加时间" == title)
        || ("RW_DB_ADD_USER" == field && "添加人" == title)
        || ("RW_DB_EDIT_TIME" == field && "修改时间" == title)
        || ("RW_DB_EDIT_USER" == field && "修改人" == title)) {
        return true;
    }
    return false;
}

/**
 * 保存基础数据
 */
function saveItemBaseDateById(rowData) {
    $.messager.confirm('系统提示', "确定保存基础数据信息吗？", function (parm) {
        if (!parm) {
            return;
        }
        var fieldArr = columns[0];
        var arr = [];
        arr.push(rowData);
        var ids = getIds(arr);
        $('#myfromdatabase').form('submit', {
            url: reportworld + "/dataBase/dataBaseUpdate",
            onSubmit: function (param) {
                var obj = new Object();
                obj.strModular = getCommbotreeValueDetail("updateModular");
                obj.strCustomer = getCommbotreeValueDetail("updateCustomer");
                obj.strReport = getCommbotreeValueDetail("updateReport");
                param.ids = JSON.stringify(ids);
                param.code = dataBaseConfig.code;
                var jsonStr = getEntityJson(fieldArr, 1);
                obj.entityJson = jsonStr;
                param.queryJson = JSON.stringify(obj);
                $.messager.progress({text: '正在处理中...',});
            }, success: function (data) {
                $.messager.progress('close');
                try {
                    data = JSON.parse(data);
                    if (successcode != data.code) {
                        return errorHandle(data);
                    }
                    //关闭弹出窗口
                    $('#dlg').dialog('close');
                    $.messager.show({title: '系统提示', msg: data.message});
                    $('#dg').datagrid("load");//刷新表格
                } catch (e) {
                    $.messager.progress('close');
                    $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
                }
            }
        });
    });
}

/**
 * 删除数据
 */
function deleteBaseDateById() {
    var arr = $('#dg').datagrid('getSelections');
    if (null == arr) {
        $.messager.alert('系统提示', "请选择要删除的数据！", 'warning');
        return;
    }
    $.messager.confirm('系统提示', "确定删除基础数据信息吗？", function (parm) {
        if (!parm) {
            return;
        }
        var ids = getIds(arr);
        var obj = new Object();
        obj.code = dataBaseConfig.code;
        obj.ids = JSON.stringify(ids);
        $('#myfromdatabase').form('submit', {
            url: reportworld + "/dataBase/deleteDataBase",
            onSubmit: function (param) {
                param.delJson = JSON.stringify(obj);
                $.messager.progress({text: '正在处理中...',});
            }, success: function (data) {
                $.messager.progress('close');
                try {
                    data = JSON.parse(data);
                    if (successcode != data.code) {
                        return errorHandle(data);
                    }
                    $.messager.show({title: '系统提示', msg: data.message});
                    $('#dg').datagrid("load");//刷新表格
                } catch (e) {
                    $.messager.progress('close');
                    $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
                }
            }
        });
    });
}

//搜索的方法
function doSearch() {
    var queryParams = $('#dg').datagrid("options").queryParams;
    var obj = new Object();
    obj.strModular = getCommbotreeValueDetail("strModular");
    obj.strCustomer = getCommbotreeValueDetail("strCustomer");
    obj.strReport = getCommbotreeValueDetail("strReport");
    obj.rwDbStatus = $('#selRwDbStatus').combobox('getValue');
    var jsonStr = "{";
    if (!isNull(dataBaseConfig.selectColumn)) {
        var arrSelectColumn = JSON.parse(dataBaseConfig.selectColumn);
        for (var columnName in arrSelectColumn) {
            jsonStr += '"' + columnName + '"' + ":" + '"' + $("#RW_DB_" + columnName).val() + '"' + ",";
        }
        jsonStr += "}";
    }
    obj.selectColumn = jsonStr;
    queryParams["queryJson"] = JSON.stringify(obj);
    $('#dg').datagrid("options").queryParams = queryParams;
    $('#dg').datagrid("load");
}

/**
 * 批量修改数据
 */
function dataBaseBatchUpdate() {
    $("#databaseview").hide();
    $("#databaseview tr").remove();
    var arr = $('#dg').datagrid('getSelections');
    if (isNull(arr)) {
        $.messager.alert('系统提示', "请选择你要修改的数据！", 'warning');
        return;
    }
    // 下拉框可编辑
    $('#rwDbVersion').combobox({
        editable: "true"
    });
    $('#rwDbStatus').combobox({
        editable: "true"
    });
    $("#myfromdatabase").form('clear');//添加之前清空表达信息
    var ids = getIds(arr);
    $('#dlg').dialog({
        title: "修改基础数据",
        buttons: [{
            text: '保存',
            iconCls: 'icon-save',
            handler: function () {
                saveItemBaseDateBatchUpdate(ids);
            }
        }, {
            text: '返回',
            iconCls: 'icon-back',
            handler: function () {
                $('#dlg').dialog('close');
            }
        }
        ]
    }).dialog('open');
    $("#myfromdatabase").form('clear');//添加之前清空表达信息
    $('#myfromdatabase').form('disableValidation');//清除验证样式
}

/**
 *  获取每个基础数据的主键字段
 * @param arr
 * @returns {Array}
 */
function getIds(arr) {
    var ids = [];
    for (var i = 0; i < arr.length; i++) {
        ids.push(arr[i][dataBaseConfig.primaryKeyColumn]);
    }
    return ids;
}

/**
 * 保存基础数据
 */
function saveItemBaseDateBatchUpdate(ids) {
    $('#myfromdatabase').form('enableValidation');//设置验证样式
    //验证表单信息
    if (!$("#myfromdatabase").form('validate')) { //验证表单信息
        return;
    }
    $.messager.confirm('系统提示', "确定保存基础数据信息吗？", function (parm) {
        if (!parm) {
            return;
        }
        $('#myfromdatabase').form('submit', {
            url: reportworld + "/dataBase/dataBaseBatchUpdate",
            onSubmit: function (param) {
                var obj = new Object();
                obj.strModular = getCommbotreeValueDetail("updateModular");
                obj.strCustomer = getCommbotreeValueDetail("updateCustomer");
                obj.strReport = getCommbotreeValueDetail("updateReport");
                obj.rwDbVersion = $('#rwDbVersion').combobox('getValue');
                obj.rwDbStatus = $('#rwDbStatus').combobox('getValue');
                param.queryJson = JSON.stringify(obj);
                param.ids = JSON.stringify(ids);
                param.code = dataBaseConfig.code;
                $.messager.progress({text: '正在处理中...',});
            }, success: function (data) {
                $.messager.progress('close');
                try {
                    data = JSON.parse(data);
                    if (successcode != data.code) {
                        return errorHandle(data);
                    }
                    //关闭弹出窗口
                    $('#dlg').dialog('close');
                    $.messager.show({title: '系统提示', msg: data.message});
                    $('#dg').datagrid("load");//刷新表格
                } catch (e) {
                    $.messager.progress('close');
                    $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
                }
            }
        });
    });
}


/**
 * 读取文件
 * @param fileName
 */
function setFilePreview(fileName) {
    $.messager.confirm('系统提示', "确定导入表信息吗？", function (parm) {
        if (!parm) {
            return;
        }
        //文件后缀格式
        if (!/\.(xlsx|XLSX)$/.test(fileName)) {
            $.messager.alert('系统提示', '错误的类型，请选择xlsx文件', 'error');
            return;
        }
        $('#subFile').form('submit', {
            url: reportworld + "/dataBase/dataBaseReadFile",
            onSubmit: function (param) {
                $.messager.progress({text: '正在处理中...'});
            }, success: function (data) {
                $.messager.progress('close');
                data = JSON.parse(data);
                $("#uploadFile").val("");
                if (successcode != data.code) {
                    return errorHandle(data);
                }
                $('#dlgMsg').dialog({
                    title: "读取数据详细信息",
                    buttons: [{
                        text: '返回',
                        iconCls: 'icon-back',
                        handler: function () {
                            $('#dlgMsg').dialog('close');
                        }
                    }
                    ]
                }).dialog('open');
                $('#dg').datagrid("load");//刷新表格
                $("#msgInfo").textbox('setValue', data.message);
            }, error: function (data) {
                $("#uploadFile").val("");
                $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
            }
        });
    });
}


/**
 * 修改变更记录信息
 */
function getDatabaseUpdateInfo() {
    var arr = $('#dg').datagrid('getSelections');
    if (null == arr || arr.length != 1) {
        $.messager.alert('系统提示', "请选择一行数据！", 'warning');
        return;
    }
    var ids = getIds(arr);
    var databaseId = ids[0];
    queryDataUpdateInfo(databaseId, dataBaseConfig.code);
}


/**
 * 导出SQL文件
 */
function dataBaseSql() {
    $('#dataBaseType').combobox('selectedIndex', 0); //选中第一个
    // 按照条件查询导出
    var jsonStr = "{";
    if (!isNull(dataBaseConfig.selectColumn)) {
        var arrSelectColumn = JSON.parse(dataBaseConfig.selectColumn);
        for (var columnName in arrSelectColumn) {
            jsonStr += '"' + columnName + '"' + ":" + '"' + $("#RW_DB_" + columnName).val() + '"' + ",";
        }
        jsonStr += "}";
    }
    var obj = new Object();
    obj.selectColumn = jsonStr;
    obj.strModular = getCommbotreeValueDetail("strModular");
    obj.strCustomer = getCommbotreeValueDetail("strCustomer");
    obj.strReport = getCommbotreeValueDetail("strReport");
    obj.rwDbStatus = $('#selRwDbStatus').combobox('getValue');
    $('#dlgExp').dialog({
        title: "导出SQL文件",
        buttons: [{
            text: '确定',
            iconCls: 'icon-save',
            handler: function () {
                $('#dlgExp').dialog('close');
                $('#tabfrom').form('submit', {
                    url: reportworld + "/dataBase/dataBaseSql",
                    onSubmit: function (param) {
                        obj.sqlType = $("#dataBaseType").combobox("getValue");
                        param.code = dataBaseConfig.code;
                        param.queryJson = JSON.stringify(obj);
                    }, success: function (data) {
                        $.messager.progress('close');
                        try {
                            data = JSON.parse(data);
                            if (successcode != data.code) {
                                return errorHandle(data);
                            }
                            $.messager.alert('系统提示', "导出数据量较大，请耐心等待！", 'info');
                        } catch (e) {
                            $.messager.progress('close');
                            $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
                        }
                    }
                });
            }
        }, {
            text: '返回',
            iconCls: 'icon-back',
            handler: function () {
                $('#dlgExp').dialog('close');
            }
        }
        ]
    }).dialog('open');
}

/**
 * 导出EXECL
 */
function dataBaseExecl() {
    // 按照条件查询导出
    var jsonStr = "{";
    if (!isNull(dataBaseConfig.selectColumn)) {
        var arrSelectColumn = JSON.parse(dataBaseConfig.selectColumn);
        for (var columnName in arrSelectColumn) {
            jsonStr += '"' + columnName + '"' + ":" + '"' + $("#RW_DB_" + columnName).val() + '"' + ",";
        }
        jsonStr += "}";
    }
    var obj = new Object();
    obj.selectColumn = jsonStr;
    obj.strModular = getCommbotreeValueDetail("strModular");
    obj.strCustomer = getCommbotreeValueDetail("strCustomer");
    obj.strReport = getCommbotreeValueDetail("strReport");
    obj.rwDbStatus = $('#selRwDbStatus').combobox('getValue');
    // 获取当前表格所有的主键信息
    $.messager.confirm('系统提示', '确定要导出EXECL数据吗？', function (param) {
        if (!param) {
            return;
        } else {
            $.messager.show({title: '系统提示', msg: "正在导出数据中，请稍后！"});
            $('#tabfrom').form('submit', {
                url: reportworld + "/dataBase/dataBaseExecl",
                onSubmit: function (param) {
                    param.queryJson = JSON.stringify(obj);
                    param.code = dataBaseConfig.code;
                }, success: function (data) {
                }
            });
        }
    })


}

/**
 * 导出zip文件
 */
function downUpgradeToolsZip() {
    // 先创建文件，在导出文件
    $.messager.progress({text: '正在处理中...',});
    $.ajax({
            type: "post",
            url: reportworld + "/upgradeToolsZip/createFile",
            dataType: "json",
            data: {},
            success: function (data) {
                $.messager.progress('close');
                if (successcode != data.code) {
                    return errorHandle(data);
                }
                downloadZipFile();
            }, error: function (data) {
                $.messager.progress('close');
                $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
            }
        }
    );
}

function downloadZipFile() {
    // 先创建文件，在导出文件
    $('#tabfrom').form('submit', {
        url: reportworld + "/upgradeToolsZip/downloadZipFile",
        onSubmit: function (param) {
        }, success: function (data) {
            try {
            } catch (e) {
                $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
            }
        }
    });
}


/**
 * 配置管理页面
 */
function viewBasedataConfig(node) {
    // 获取信息加载到页面
    $.ajax({
            type: "post",
            url: reportworld + "/dataBase/dataBaseManager",
            dataType: "json",
            data: {
                code: node.attributes
            },
            success: function (data) {
                $.messager.progress('close');
                if (successcode != data.code) {
                    return errorHandle(data);
                }
                $('#dlgDataManager').dialog('open');
                $('#myformDataManager').form('clear');//添加之前清空表达信息
                $('#myformDataManager').form('enableValidation');//设置验证样式
                $('#code').val(node.attributes); // 选择的当前的配置表编码
                if (!isNull(data.data.list)) {
                    $("#onlyColumn").combobox("loadData", data.data.list);
                    $("#showColumnConfig").combobox("loadData", data.data.list);
                    $("#primaryKeyColumnReal").combobox("loadData", data.data.list);
                }
                var orderColumnList = data.data.orderColumnList;
                var selectColumnList = data.data.selectColumnList;
                if (!isNull(orderColumnList)) {
                    $("#orderColumn").combobox("loadData", orderColumnList);
                }
                if (!isNull(selectColumnList)) {
                    $("#selectColumn").combobox("loadData", selectColumnList);
                }
                if (!isNull(data.data.databaseConfig)) {
                    $('#databaseId').val(data.data.databaseConfig.databaseId);//页面赋值
                    $('#configId').val(data.data.databaseConfig.id);//页面赋值
                    $('#primaryKeyColumnReal').combobox('setValue', data.data.databaseConfig.primaryKeyColumnReal);//页面赋值
                    $('#onlyColumn').combobox('setValues', data.data.databaseConfig.onlyColumn);//页面赋值
                    $('#dataType').combobox('setValue', data.data.databaseConfig.dataType);//页面赋值
                    $('#statusConfig').combobox('setValue', data.data.databaseConfig.status);//页面赋值
                } else { //没有配置信息
                    $('#databaseId').val(node.id)// 选择的当前的配置表ID
                    $('#dataType').combobox('selectedIndex', 1); //选中第一个
                    $('#statusConfig').combobox('selectedIndex', 0); //选中第一个
                }
                if (!isNull(data.data.listShowColumn)) {
                    $('#showColumnConfig').combobox('setValues', data.data.listShowColumn);//页面赋值
                }
                if (!isNull(data.data.listSelectColumn)) {
                    $('#selectColumn').combobox('setValues', data.data.listSelectColumn);//页面赋值
                }
                if (!isNull(data.data.listOrderColumn)) {
                    $('#orderColumn').combobox('setValues', data.data.listOrderColumn);//页面赋值
                }
                $('#myformDataManager').form('enableValidation');//设置验证样式
            }, error: function (data) {
                $.messager.progress('close');
                $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
            }
        }
    );
}

/**
 * 保存基础数据配置信息
 */
function saveDataBaseConfig() {
    $('#myformDataManager').form('submit', {
        url: reportworld + "/dataBase/saveDataBaseConfig",
        onSubmit: function (param) {
            $.messager.progress({text: '正在处理中...'});
        }, success: function (data) {
            $.messager.progress('close');
            try {
                $.messager.progress('close');
                data = JSON.parse(data);
                if (successcode != data.code) {
                    return errorHandle(data);
                }
                $('#dlgDataManager').dialog('close');
                $.messager.show({title: '系统提示', msg: data.message});
            } catch (e) {
                $.messager.progress('close');
                $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
            }
        }
    });
}

/**
 * 添加基础信息弹出框
 */
function addDataBase() {
    $("#myformDataBase").form('clear');//添加之前清空表达信息
    $('#myformDataBase').form('enableValidation');//设置验证样式
    $('#dlgDataBase').dialog({
        title: "新增基础数据信息",
        buttons: [{
            text: '保存',
            iconCls: 'icon-save',
            handler: function () {
                saveItemDataBase(1);
            }
        }, {
            text: '返回',
            iconCls: 'icon-back',
            handler: function () {
                $('#dlgDataBase').dialog('close');
            }
        }
        ]
    }).dialog('open');
    var node = $("#treeContent").tree('getSelected');
    $('#parentId').combotree('setValue', node.id);
}

/**
 * 修改基础信息
 */
function editDataBase() {
    $('#myformDataBase').form('enableValidation');//设置验证样式
    $('#dlgDataBase').dialog({
        title: "编辑基础数据信息",
        buttons: [{
            text: '保存',
            iconCls: 'icon-save',
            handler: function () {
                saveItemDataBase(2);
            }
        }, {
            text: '返回',
            iconCls: 'icon-back',
            handler: function () {
                $('#dlgDataBase').dialog('close');
            }
        }
        ]
    }).dialog('open');
    getDataBaseInfo()
}

/**
 * 点击树节点加载对应机构信息
 * @param orgId
 */
function getDataBaseInfo() {
    var node = $("#treeContent").tree('getSelected');
    $.messager.progress({text: '正在加载中...',});
    $.ajax({
            type: "post",
            url: reportworld + "/dataBase/queryDataBaseInfo",
            dataType: "json",
            data: {
                id: node.id
            },
            success: function (data) {
                $.messager.progress('close');
                if (successcode != data.code) {
                    return errorHandle(data);
                }
                $('#myformDataBase').form('load', data.data);//页面赋值
            }, error: function (data) {
                $.messager.progress('close');
                $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
            }
        }
    );
}

//保存机构信息
function saveItemDataBase(ftype) {
    //验证表单信息
    if (!$("#myformDataBase").form('validate')) { //验证表单信息
        return;
    }
    var url = reportworld + "/dataBase/edit";
    if (1 == ftype) {
        url = reportworld + "/dataBase/add";
    }
    $.messager.confirm('系统提示', "确定保存基础数据信息吗？", function (parm) {
        if (!parm) {
            return;
        }
        $('#myformDataBase').form('submit', {
            url: url,
            onSubmit: function () {
                $.messager.progress({text: '正在处理中...',});
            }, success: function (data) {
                $.messager.progress('close');
                try {
                    data = JSON.parse(data);
                    if (successcode != data.code) {
                        return errorHandle(data);
                    }
                    //关闭弹出窗口
                    $('#dlgDataBase').dialog('close');
                    getBaseDataTree();//刷新树
                    initData();
                    $.messager.show({title: '系统提示', msg: data.message});
                } catch (e) {
                    $.messager.progress('close');
                    $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
                }
            }
        });
    });
}

// 删除基础信息
function delDataBase() {
    var node = $("#treeContent").tree('getSelected');
    $.messager.confirm('系统提示', '确定要删除【' + node.text + '】基础数据以及下级所有基础数据配置吗？', function (param) {
        if (!param) {
            return;
        }
        $.messager.progress({text: '正在处理中...',});
        $.ajax({
                type: "post",
                url: reportworld + "/dataBase/del",
                dataType: "json",
                data: {
                    id: node.id
                },
                success: function (data) {
                    $.messager.progress('close');
                    if (successcode != data.code) {
                        return errorHandle(data);
                    }
                    getBaseDataTree();//刷新树
                    initData();
                    $.messager.show({title: '系统提示', msg: data.message});
                }, error: function (data) {
                    $.messager.progress('close');
                    $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
                }
            }
        );

    });
}

/**
 * 据对比策略信息
 */
function viewCompareconfig() {
    // 获取信息加载到页面
    $.ajax({
            type: "post",
            url: reportworld + "/compareconfig/queryCompareconfig",
            dataType: "json",
            data: {},
            success: function (data) {
                $.messager.progress('close');
                if (successcode != data.code) {
                    return errorHandle(data);
                }
                $('#dlgCompareconfig').dialog('open');
                $('#myformCompareconfig').form('clear');//添加之前清空表达信息
                $('#myformCompareconfig').form('enableValidation');//设置验证样式
                $('#myformCompareconfig').form('load', data.data);//页面赋值
                $('#myformCompareconfig').form('enableValidation');//设置验证样式
            }, error: function (data) {
                $.messager.progress('close');
                $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
            }
        }
    );
}

/**
 * 保存基础数据配置信息
 */
function saveCompareconfig() {
    $('#myformCompareconfig').form('submit', {
        url: reportworld + "/compareconfig/edit",
        onSubmit: function (param) {
            $.messager.progress({text: '正在处理中...'});
        }, success: function (data) {
            $.messager.progress('close');
            try {
                $.messager.progress('close');
                data = JSON.parse(data);
                if (successcode != data.code) {
                    return errorHandle(data);
                }
                $('#dlgCompareconfig').dialog('close');
                $.messager.show({title: '系统提示', msg: data.message});
            } catch (e) {
                $.messager.progress('close');
                $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
            }
        }
    });
}


/**
 * 更新校验语句
 */
function updateCheckDataBase() {
    $.messager.progress({text: '正在处理中...',});
    $.ajax({
            type: "post",
            url: reportworld + "/dataBase/updateCheckDataBase",
            dataType: "json",
            data: {},
            success: function (data) {
                $.messager.progress('close');
                if (successcode != data.code) {
                    return errorHandle(data);
                }
            }, error: function (data) {
                $.messager.progress('close');
                $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
            }
        }
    );
}


/**
 * 导出校验文件
 */
function queryCheckDataBaseInfoAll() {
    $('#tabfrom').form('submit', {
        url: reportworld + "/dataBase/queryCheckDataBaseInfoAll",
        onSubmit: function (param) {
        }, success: function (data) {
            try {

            } catch (e) {
                $.messager.progress('close');
                $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
            }
        }
    });
}

